package com.limh.socketdemo

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.limh.socketdemo.bean.MsgEvent
import com.limh.socketdemo.bean.Type
import com.limh.socketdemo.service.utils.StreamToolkit
import com.limh.socketdemo.service.WebConfiguration
import com.limh.socketdemo.service.client.HttpClient
import com.limh.socketdemo.service.resource.ResourceAddressHandler
import com.limh.socketdemo.service.server.HttpServer
import com.limh.socketdemo.utils.GsonUtils
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    lateinit var server: HttpServer
    lateinit var webServerConfig: WebConfiguration

    lateinit var client: HttpClient
    lateinit var webClientConfig: WebConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        EventBus.getDefault().register(this)
        initViews()
    }

    private fun initViews() {
        webServerConfig = WebConfiguration()
        webServerConfig.address = StreamToolkit.getLocalIp(this)
        webServerConfig.port = 8088
        Log.d(TAG, "address=$webServerConfig")
        btnOpenServer.setOnClickListener {
            server = HttpServer(webServerConfig)
            //注册处理client消息的handler
            server.registerResourceHandler(ResourceAddressHandler())
            server.startASync()
            txtServer.append("服务器启动：${webServerConfig.address}")
        }
        webClientConfig = WebConfiguration()
        webClientConfig.address = "192.168.31.49"
        webClientConfig.port = 8088

        btnOpenClient.setOnClickListener {
            client = HttpClient(webClientConfig)
            val msgEvent = MsgEvent()
            msgEvent.code = Type.TYPE_AUTH
            msgEvent.any = "我是来自客户端消息"
            client.send("/auth", GsonUtils.bean2Str(msgEvent))
            txtClient.append("连接服务器：${webClientConfig.address}\n")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getMessage(msgEvent: MsgEvent) {
        Log.d(TAG, "eventBus收到：" + msgEvent.toString())
        when (msgEvent.code) {
            Type.TYPE_AUTH -> txtServer.append("\n${msgEvent.any.toString()}")
            Type.TYPE_CLIENT -> txtClient.append("\n${msgEvent.any.toString()}")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        server.stopASync()
    }

}
